package com.example.app.domain.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.util.Random;
//import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * Title:Server 这是发送消息的服务端
 * Description: 服务器向多个客户端推送主题，即不同客户端可向服务器订阅相同主题
 *
 * @author Unclue_liu
 */


@Component
public class ServerMQTT {

    //tcp://MQTT安装的服务器地址:MQTT定义的端口号
    public static final String HOST = "ws://127.0.0.1:8083/mqtt";
    //定义一个主题
    public static final String TOPIC = "testtopics";
    //定义MQTT的ID，可以在MQTT服务配置中指定
    private static final String clientid = "server11";

    private MqttClient client;
    private static MqttTopic topic11;
//    private String userName = "mqtt";  //非必须
//    private String passWord = "mqtt";  //非必须

    private static MqttMessage message;

    /**
     * 构造函数
     *
     * @throws MqttException
     */
    public ServerMQTT() throws MqttException {
        // MemoryPersistence设置clientid的保存形式，默认为以内存保存
        client = new MqttClient(HOST, clientid, new MemoryPersistence());
        connect();
    }

    /**
     * 用来连接服务器
     */
    private void connect() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
//        options.setUserName(userName);
//        options.setPassword(passWord.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            client.setCallback(new PushCallback());
            client.connect(options);
            topic11 = client.getTopic(TOPIC);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param topic
     * @param message
     * @throws MqttPersistenceException
     * @throws MqttException
     */
    public static void publish(MqttTopic topic, MqttMessage message) throws MqttPersistenceException,
            MqttException {
        MqttDeliveryToken token = topic.publish(message);

        token.waitForCompletion();
        System.out.println("message is published completely! "
                + token.isComplete());
    }


    //    public static void sendMessage(String str1,String str2,String str3)throws Exception{
//        public static void sendMessage(String str)throws Exception{
    public static void sendMessage(String arr1[], String arr2[], String arr3[], String arr4[]) throws Exception {
        ServerMQTT server = new ServerMQTT();
        server.message = new MqttMessage();
        server.message.setQos(1);  //保证消息能到达一次
        server.message.setRetained(true);
        int flag;
        /*--------------------------------页面--------------------------------------*/
        Random random = new Random();
        DecimalFormat df = new DecimalFormat("0.00");
        String[] str1 = new String[6];
        String[] str2 = new String[4];
        String[] str3 = new String[3];
        String[] str4 = new String[5];
        for (int i = 0; i < 6; i++) {
            double number = random.nextDouble() * 180 + 100;
            str1[i] = df.format(number);
        }
        for (int i = 0; i < 4; i++) {
            double number = random.nextDouble() * 90 + 10;
            str2[i] = df.format(number);
        }
        for (int i = 0; i < 3; i++) {
            double number = random.nextDouble() * (1 - 0);
            str3[i] = df.format(number);
        }
        for (int i = 0; i < 5; i++) {
            double number = random.nextDouble() * 500 + 100;
            str4[i] = df.format(number);
        }
        /*--------------------------------页面--------------------------------------*/
//            if((System.currentTimeMillis() / 1000)%2==0)
//                flag=0;
//            else
//                flag=1;
//
//        String strs="{\"id\":\"07717d6\",\"showChild\":\""+flag+"\"}";

        String strs =
                "[{\"id\":\"f0f300\",\"text\":\"" + arr1[0] + "\"},{\"id\":\"336632db\",\"text\":\"" + arr1[1] + "\"}," +
                        "{\"id\":\"491fde5\",\"text\":\"" + arr1[2] + "\"},{\"id\":\"7cb97f30\",\"text\":\"" + arr1[3] +
                        "\"},{\"id\":\"d91ef57\",\"text\":\"" + arr1[4] + "\"},{\"id\":\"3137f06\",\"text\":\"" + arr1[5] +
                        "\"},{\"id\":\"56b080b3\",\"text\":\"" + arr1[6] + "\"},{\"id\":\"558fc68e\",\"text\":\"" + arr2[0] +
                        "\"},{\"id\":\"5088430\",\"text\":\"" + arr2[1] + "\"},{\"id\":\"216309a\",\"text\":\"" + arr2[2] +
                        "\"},{\"id\":\"7dbccfe\",\"text\":\"" + arr2[3] + "\"},{\"id\":\"78093804\",\"text\":\"" + arr1[4] +
                        "\"},{\"id\":\"4d0c17b9\",\"text\":\"" + arr2[5] + "\"},{\"id\":\"f84c6bb\",\"text\":\"" + arr1[6] +
                        "\"}, {\"id\":\"7f70c961\",\"text\":\"" + arr3[0] + "\"},{\"id\":\"26d174ae\",\"text\":\"" + arr3[1] +
                        "\"},{\"id\":\"4a79ca4b\",\"text\":\"" + arr3[2] + "\"},{\"id\":\"f6287e5\",\"text" + "\":\"" + arr3[3] +
                        "\"},{\"id\":\"5fefd437\",\"text\":\"" + arr3[4] + "\"},{\"id\":\"3483a14\",\"text\":\"" + arr3[5] +
                        "\"},{\"id\":\"368a556\",\"text\":\"" + arr4[0] + "\"},{\"id\":\"ff7d8a5\",\"text\":\"" + arr4[1] +
                        "\"},{\"id\":\"256965a\",\"text\":\"" + arr4[2] + "\"},{\"id\":\"2d7e6845\",\"text\":\"" + arr4[3] +
                        "\"},{\"id\":\"66871ed4\",\"text\":\"" + arr4[4] + "\"},{\"id\":\"6248a0\",\"text\":\"" + arr4[5] +
                        "\"},{\"id\":\"a0b4559\",\"text\":\"" + arr4[6] + "\"},{\"id\":\"8165e78\",\"text\":\"" + str1[0] +
                        "\"},{\"id\":\"27e70d68\",\"text\":\"" + str1[1] + "\"},{\"id\":\"749a2c6c\",\"text\":\"" + str1[2] +
                        "\"},{\"id\":\"830d60c\",\"text\":\"" + str1[3] + "\"},{\"id\":\"8b80c72\",\"text\":\"" + str1[4] +
                        "\"},{\"id\":\"bfd447e\",\"text\":\"" + str1[5] + "\"},{\"id\":\"a035145\",\"text\":\"" + str2[0] +
                        "\"},{\"id\":\"4f77285\",\"text\":\"" + str2[1] + "\"},{\"id\":\"42f427ab\",\"text\":\"" + str2[2] +
                        "\"},{\"id\":\"4fdb0d40\",\"text\":\"" + str2[3] + "\"},{\"id\":\"7e9ef4\",\"text\":\"" + str3[0] +
                        "\"},{\"id\":\"89ce20d\",\"text\":\"" + str3[1] + "\"},{\"id\":\"77c0f14e\",\"text\":\"" + str4[0] +
                        "\"},{\"id\":\"2d13359d\",\"text\":\"" + str4[1] + "\"},{\"id\":\"6fbc373f\",\"text\":\"" + str4[2] +
                        "\"},{\"id\":\"552821b\",\"text\":\"" + str4[3] + "\"},{\"id\":\"51102422\",\"text\":\"" + str4[4] +
                        "\"},{\"id\":\"4e2cab58\",\"text\":\"" + str3[0] + "\"}]";


        //            {"id":"19191","text":""+arr1[2]+""}
//        String strs ="[{\"id\":\"96a126\",\"text\":\""+str1+"\"},{\"id\":\"65ae0673\",\"text\":\""+str2+"\"}," +
//                "{\"id\":\"35bef1e9\",\"text\":\""+str3+"\"}]";

//        String strs= "{ \"id\": \"96a126\", \"text\": \""+arr1+"\",\""+arr2+"\"}" ;
// String strs= "{\"id\":\"96a126\",\"text\":\"[[\""+arr1[0]+"\",\""+arr1[1]+"\",\""+arr1[2]+"\",\""+arr1[3]+ "\",\""+arr1[4]+"\",\""+arr1[5]+"\",\""+arr1[6]+"\"],[\""+arr2[0]+"\",\""+arr2[1]+"\",\""+arr2[2]+"\",\""+arr2[3]+"\",\""+arr2[4]+"\",\""+arr2[5]+"\",\""+arr2[6]+"\"]]\"}";

        //        String strs="[{\"children\":[{\"children\":[{\"id\":\"d-1-a-001\",\"name\":\"车辆\"},{\"id\":\"d-1-a-002\"," +
//                "\"name\":\"访客\"}],\"id\":\"device-001-a\",\"name\":\"园区大门\"},{\"children\":[{\"id\":\"d-1-b-001\",\"name\":\"湿度\"},{\"id\":\"d-1-b-002\",\"name\":\"浇水\"}],\"id\":\"device-001-b\",\"name\":\"1号草坪\"}],\"id\":\"device-001\",\"name\":\"新智慧园区\"},{\"children\":[{\"children\":[{\"id\":\"d-2-a-001\",\"name\":\"温度\"},{\"id\":\"d-2-a-002\",\"name\":\"湿度\"},{\"id\":\"d-2-a-003\",\"name\":\"空调\"},{\"id\":\"d-2-a-004\",\"name\":\"智能窗帘\"}],\"id\":\"device-002-a\",\"name\":\"客厅\"},{\"children\":[{\"id\":\"d-2-b-001\",\"name\":\"温度\"},{\"id\":\"d-2-b-002\",\"name\":\"湿度\"},{\"id\":\"d-2-b-003\",\"name\":\"空调\"}],\"id\":\"device-002-b\",\"name\":\"主卧\"},{\"children\":[{\"id\":\"d-2-c-001\",\"name\":\"温度\"},{\"id\":\"d-2-c-002\",\"name\":\"湿度\"},{\"id\":\"d-2-c-003\",\"name\":\"空调\"}],\"id\":\"device-002-c\",\"name\":\"次卧\"},{\"children\":[{\"id\":\"d-2-d-001\",\"name\":\"温度\"},{\"id\":\"d-2-d-002\",\"name\":\"湿度\"},{\"id\":\"d-2-d-003\",\"name\":\"空调\"}],\"id\":\"device-002-d\",\"name\":\"儿童房\"},{\"children\":[{\"id\":\"d-2-e-001\",\"name\":\"温度\"},{\"id\":\"d-2-e-002\",\"name\":\"湿度\"},{\"id\":\"d-2-e-003\",\"name\":\"空调\"}],\"id\":\"device-002-e\",\"name\":\"书房\"}],\"id\":\"device-002\",\"name\":\"智能家居\"},{\"children\":[{\"children\":[{\"id\":\"d-3-a-001\",\"name\":\"户数\"},{\"id\":\"d-3-a-002\",\"name\":\"电压\"},{\"id\":\"d-3-a-003\",\"name\":\"电流\"}],\"id\":\"device-003-a\",\"name\":\"1号小区\"},{\"children\":[{\"id\":\"d-3-b-001\",\"name\":\"户数\"},{\"id\":\"d-3-b-002\",\"name\":\"电压\"},{\"id\":\"d-3-b-003\",\"name\":\"电流\"}],\"id\":\"device-003-b\",\"name\":\"2号小区\"}],\"id\":\"device-003\",\"name\":\"电力能源\"}]";

//    String strs= "{\"id\":\"96a126\",\"text\":[\""+arr1[0]+"\",\""+arr1[1]+","+arr1[2]+","+arr1[3]+","+arr1[4]+". "+arr1[5]+","+arr1[6]+","+arr1[7]+"],["+arr2[0]+","+arr2[1]+","+arr2[2]+","+arr2[3]+","+arr2[4]+"."+arr2[5]+","+arr2[6]+","+arr2[7]+"]}";

        server.message.setPayload(strs.getBytes());
        try {
            publish(server.topic11, server.message);
            //断开连接
//            server.client.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//    @Scheduled(fixedDelay = 1000 * 10)
//    public static void doTask(){
//        System.out.println("定时任务~");
//    }

    /**
     * 启动入口
     *
     * @param args
     * @throws MqttException
     */
//    @Scheduled(cron = "*/2 * * * * ?")
    public static void main(String[] args) throws Exception {
//        sendMessage("b634e25","lalalalal");
        String str = Long.toString(System.currentTimeMillis());
        double d = Double.parseDouble(str);
//        sendMessage(str);
        //System.out.println("我是定时任务~");
//        doTask();


//        TimerTask timerTask = new TimerTask() {
//            @Override
//            public void run() {
//                System.out.println("打印当前时间：" + new Date());
//            }
//        };
//        // 计时器
//        Timer timer = new Timer();
//        // 开始执行任务 (延迟1000毫秒执行，每3000毫秒执行一次)
//        timer.schedule(timerTask, 1000, 1000);


//        if((System.currentTimeMillis()/1000)%2!=0)
//            sendMessage("[{  \"id\": \"35bef1e9\",   \"text\": str},{\"id\": \"65ae0673\",   " + "\"text\":\"48.5 " +
//                    "!!!\"},{  \"id\": \"5ab01af\",   \"text\":\"300.8\" }]");
//        else
//            sendMessage("[{  \"id\": \"35bef1e9\",   \"text\":\"lalalalala\" },{\"id\": \"65ae0673\",   " + "\"text\":\"48.5 " + "!!!\"},{  \"id\": \"5ab01af\",   \"text\":\"300.8\" }]");

        //        sendMessage("{  \"id\": \"aef3d5\",   \"text\":\"amazing\" }");
//        [{  "id": "aef3d5",   "text":"hello !!!" },{"id": "98b8ad9",   "text":"bye !!!"}]
//        System.out.println("当前时间为："+System.currentTimeMillis()+"毫秒");
    }


}

//1 创建两个
//2 实时更新，间隔2s？